import { ref } from 'vue'
import { defineStore } from 'pinia'
import { computedAsync } from '@vueuse/core'
import api from '@/api/ebook'
import type { HashSet, LessonItem, EbookItem, EbookCreateItem } from '@/config/types'


export const useEbookStore = defineStore('ebook', () => {
  const loading = ref<boolean>(false)
  const ebooks = ref<EbookItem[]>([])
  const currentLessonId = ref<number>(0)
  const lessonCaches = ref<HashSet<LessonItem>>({})

  const lesson = computedAsync(async () => {
    if (currentLessonId.value === 0) {
      return null
    }
    if (lessonCaches.value[currentLessonId.value]) {
      return lessonCaches.value[currentLessonId.value]
    }
    await loadLesson(currentLessonId.value)
    return lessonCaches.value[currentLessonId.value]
  }, null)

  async function loadEbooks(lessonId: number) {
    loadLesson(lessonId)
    loading.value = true
    try {
      const res = await api.getList(lessonId)
      ebooks.value = res.data
      loading.value = false
    } catch (e) {
      loading.value = false
    }
  }

  async function loadLesson(lessonId: number) {
    currentLessonId.value = lessonId
    if (!lessonCaches.value[lessonId]) {
      const res = await api.getLesson(lessonId)
      lessonCaches.value[lessonId] = res.data
    }
  }

  async function deleteEbook(id: number) {
    loading.value = true
    try {
      const res = await api.delete(id)
      loading.value = false
      return res.data
    } catch (e) {
      loading.value = false
    }
  }

  async function createBatch(lessonId: number, items: EbookCreateItem[]) {
    await api.createBatch({
      lessonId,
      files: items.map((item: EbookCreateItem) => {
        return {
          title: item.title,
          file: item.file,
          sort: item.sort
        }
      })
    })
  }

  async function updateOnself(val: boolean) {
    const ids = ebooks.value.filter((item) => item.onself === val).map((item) => item.id)
    await api.onself(ids, val)
  }

  return {
    loading,
    ebooks,
    lesson,
    loadEbooks,
    deleteEbook,
    createBatch,
    updateOnself
  }
})
